import datetime
import json

import openpyxl
from selenium import webdriver
from time import sleep
from selenium.webdriver.chrome.service import Service
import pymysql
import csv

from selenium.webdriver.chrome.webdriver import WebDriver

from config.config import *
import config.config

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options


def open_browsers():
    """
    加载驱动，关闭密码提示弹窗，浏览器窗口最大化，返回浏览器对象
    :return: 浏览器对象
    """
    # chrome_options = Options()

    # 关闭保存密码和密码泄露检测弹窗
    # prefs = {
    #     "credentials_enable_service": False,
    #     "profile.password_manager_enabled": False
    # }
    # chrome_options.add_experimental_option("prefs", prefs)
    # chrome_options.add_argument("--disable-features=PasswordLeakDetection")
    #
    # # 去掉“Chrome正受到自动化测试软件控制”的提示
    # chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    # chrome_options.add_experimental_option('useAutomationExtension', False)
    # ========================

    options = Options()

    prefs = {
        "profile.password_manager_leak_detection": False,
        "credentials_enable_service": False,
        "profile.password_manager_enabled": False
    }
    options.add_experimental_option("prefs", prefs)
    # ========================

    service = Service(DRIVER_PATH)
    driver = webdriver.Chrome(service=service, options=options)
    # driver = webdriver.Chrome(service=service, options=chrome_options)

    driver.maximize_window()
    return driver


# 读取txt文件
def read_txt(filename="../datas/crm_login.txt"):
    data_list = []
    with open(filename, "r", encoding="utf8") as f:
        for line in f:
            data = line.strip().split(",")
            data_list.append(data)
        print(data_list)


# excel文件参数化
def read_excel(filename="../datas/crm_login.xlsx", workbook_name=None):
    """
    读取excel文件数据并处理
    :return: 返回处理好的excel数据
    """
    wb = openpyxl.load_workbook(filename)
    sheet = wb[workbook_name]  # 根据工作表名获取工作表
    # 拿到所有行
    rows = sheet.iter_rows(min_row=2)
    # 一行一行拿取单元格数据
    datas = []  # 最终的数据
    for row in rows:
        row_list = []
        for cell in row:
            row_list.append(cell.value)
        datas.append(row_list)
    return datas


# csv文件参数化
def read_csv(filename=r"E:\pythonProject\UnitTest\datas\crm_login.csv"):
    """
    处理csv数据文件
    :param filename:csv文件路徑
    :return: 处理好的csv数据，格式是列表,列表中每个元素都是列表，元素列表里面每一行的数据
    """
    # f = open(filename, 'r', encoding='utf-8')
    # datas = csv.reader(f)
    # data_list = []
    #
    # # for data in datas:      # data是一行数据,类型为列表,格式为['url', ' expect_url', 'username', 'password']
    # #     print(data)
    # #     data_list.append(data)
    # # print("result")
    # # print(data_list)
    # # f.close()

    with open(filename, 'r', encoding='utf-8') as f:
        datas = csv.reader(f)
        next(datas)  # 使用next()跳过第一行表头
        data_list = [row for row in datas]  # 读取剩下的数据
    return data_list


# 数据库参数化
class DB:
    """
    处理数据库数据的类
    """

    def __init__(self, host=None, user=None, password=None, db=None):
        self.host = host if host else "localhost"
        self.user = user if user else "root"
        self.password = password if password else ""
        self.db = db if db else "test"
        self.config = {
            "host": self.host,
            "user": self.user,
            "password": self.password,
            "db": self.db
        }
        self.connect = None
        self.cursor = None

    def query(self, sql):
        self.connect = pymysql.connect(**self.config)
        self.cursor = self.connect.cursor()
        self.cursor.execute(sql)
        datas = self.cursor.fetchall()
        return datas

    # 魔术方法自动执行,关闭游标和链接
    def __del__(self):
        self.cursor.close()
        self.connect.close()


def get_current_month_name(num: int):
    """
    获取当前月份名称（中文）
    :param num:num=1为当前月，num=2,为上个月，num=0,为下个月
    :return:月份
    """
    current_month = datetime.datetime.now().month
    month_names = ["一月", "二月", "三月", "四月", "五月", "六月",
                   "七月", "八月", "九月", "十月", "十一月", "十二月"]
    return month_names[current_month - num]


if __name__ == '__main__':
    pass
    # open_browsers()  # 调试浏览器
    # print(read_excel())  # 调试csv读取文件
    # print(read_csv())  # 调试excel读取文件
    # read_txt()
    # print(get_current_month_name(0))
